package com.hyl.servlet;/**
 * DispatherServelt
 *
 * @author hyl
 * @date 2024-12-04
 */

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

//@WebServlet(name = "DispatherServelt", value = "/")
public class DispatherServelt extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

/*
* <a herf="/hyl/user/list?username=hyl&password=123456">跳转</a>
* <a herf="/hyl/dept/add">跳转</a>
* */

    static Map<String,String> map = new HashMap<>();
    static {
        map.put("user","com.hyl.servlet.UserController");
        map.put("dept","com.hyl.servlet.DeptController");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过请求的路径，使用反射，生成类=》实现方法调用
        response.setContentType("text/html");

        //获取请求的路径
        String path = request.getServletPath().substring(1);
        System.out.println("请求路径："+path);
        //拆分请求的路径
        String[] tmp = path.split("/");
        try {
            //获取请求的对象
            Class obj = Class.forName(map.get(tmp[1]));
            //实例化操作的真实对象
            BaseController baseController = (BaseController) obj.newInstance();
            //执行方法
            String view =  baseController.execute(tmp[2],request);
            //返回结果，视图
            String[] ret = view.split(":");
            if(ret[0].equals("redirect")){
                response.sendRedirect(ret[1]);
            }else if(ret[0].equals("forward")){
                request.getRequestDispatcher(ret[1]).forward(request, response);
            }else{
                PrintWriter  out = response.getWriter();
                out.println("<script type=\"text/javascript\">");
                out.println("alert("+ret[1]+")");
                out.println("</script>");
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

//        //转发==> forward:index.html
//        request.getRequestDispatcher("index.html").forward(request, response);
//        //重定向==> redirect:index.html
//        response.sendRedirect("index.html");
//        //异步==>ajax:msg
//        response.getWriter().print("haha");
    }
}
